package com.huntmobi.springsecuritydemo.base.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.huntmobi.springsecuritydemo.base.enums.ContextTypeEnum;
import com.huntmobi.springsecuritydemo.base.enums.HttpEnum;
import com.huntmobi.springsecuritydemo.base.http.Request;
import com.huntmobi.springsecuritydemo.base.http.Response;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @BelongsProject: spring-security-demo
 * @BelongPackage: com.huntmobi.springsecuritydemo.base.filter
 * @Author: zouzhimin
 * @Date: 2020/11/19 15:28
 * @Description: 无权限，json返回
 **/
@Component
public class JsonAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        httpServletResponse.setContentType(ContextTypeEnum.JSONUTF8.getContextType());
        PrintWriter out = httpServletResponse.getWriter();
        Request result = Response.error(HttpEnum.NOPERMISSION.getCode(), "接口：【" + httpServletRequest.getRequestURI() + "】" + HttpEnum.NOPERMISSION.getMsg());
        out.write(new ObjectMapper().writeValueAsString(result));
        out.flush();
        out.close();
    }
}
